package com.chensq.devops

import org.apache.commons.text.StringEscapeUtils
import java.net.URLEncoder

def getObject(String project, String receiver, String credentialsId, String title) {
    this.project = project
    this.receiver = receiver
    this.credentialsId = credentialsId
    this.title = title
    return this
}

def notification(String type) {
    String msg = "\uD83D\uDE04👍 CI/CD${this.title} 👍😄"

    if (this.title == "") {
        msg = "\uD83D\uDC4D CI/CD\u6D41\u6C34\u7EBF\u6210\u529F\u5566 \uD83D\uDC4D\uD83D\uDE04"
    }
    // failed
    if (type == "failure") {
        msg = "\u274C\uD83D\uDE16 CI/CD \u6D41\u6C34\u7EBF\u5931\u8D25\u4E86 \u274C\uD83D\uDE16"
        if (this.title == "") {
            msg = "\u274C\uD83D\uDE16 CI/CD \u6D41\u6C34\u7EBF\u5931\u8D25\u4E86 \u274C\uD83D\uDE16"
        }
    }
    String title = msg
    // rich notify msg
    msg = genNotificationMessage(msg)
    if (this.receiver == "dingTalk") {
        try {
            new DingTalk().markDown(title, msg, this.credentialsId)
        } catch (Exception ignored) {}
    } else if (this.receiver == "wechat") {
        //todo
    } else if (this.receiver == "email") {
        //todo
    } else {
        error "no support notify type!"
    }
}

def genNotificationMessage(msg) {
    // project
    msg = "${msg}  \n  \u9879\u76EE\u540D\u79F0: ${this.project}"
    // get git log
    def gitlog = ""
    try {
        sh "git log --oneline -n 1 > gitlog.file"
        gitlog = readFile "gitlog.file"
    } catch (Exception ignored) {}

    if (gitlog != null && gitlog != "") {
        msg = "${msg}  \n  **Git log**: ${gitlog}"
    }
    // get git branch
    def gitbranch = env.BRANCH_NAME
    if (gitbranch != null && gitbranch != "") {
        msg = "${msg}  \n  **Git branch**: ${gitbranch}"
    }
    // build tasks
    msg = "${msg}  \n  **Build Tasks**: ${env.BUILD_TASKS}"

    // get buttons
    msg = msg + getButtonMsg()
    return msg
}

def getButtonMsg() {
    String res = ""
    def buttons = [
        [
            "title": "\u67E5\u770B\u6D41\u6C34\u7EBF",
            "actionURL": org.apache.commons.text.StringEscapeUtils.escapeEcmaScript(env.RUN_DISPLAY_URL),
        ],
        // [
        //     "title": "\u4EE3\u7801\u626B\u63CF\u7ED3\u679C",
        //     "actionURL": "http://sonar.luffy.com/dashboard?id=${this.project}"
        // ]
    ]
    buttons.each() {
        if (res == "") {
            res = "   \n >"
        }
        res = "${res} --- [" + it["title"] + "](" + it["actionURL"] + ") "
    }
    return res
}
